use crate::{
    error::Error,
    reservation::QueryRequest,
    utils::{convert_to_timestamp, convert_to_utc_time},
};
use chrono::{DateTime, Utc};
use std::ops::Range;

use super::{Validator, validate_range};

impl Validator for QueryRequest {
    fn validate(&self) -> Result<(), Error> {
        validate_range(self.start.as_ref(), self.end.as_ref())?;
        Ok(())
    }
}

impl QueryRequest {
    pub fn new(
        resource_id: impl Into<String>,
        user_id: impl Into<String>,
        status: i32,
        start: DateTime<Utc>,
        end: DateTime<Utc>,
        page: i32,
        page_size: i32,
        desc: bool,
    ) -> Self {
        Self {
            resource_id: resource_id.into(),
            user_id: user_id.into(),
            start: Some(convert_to_timestamp(start)),
            end: Some(convert_to_timestamp(end)),
            status,
            page,
            page_size,
            desc,
        }
    }

    pub fn get_timespan(&self) -> Range<DateTime<Utc>> {
        let start = convert_to_utc_time(*self.start.as_ref().unwrap());
        let end = convert_to_utc_time(*self.end.as_ref().unwrap());
        Range { start, end }
    }
}
